//
//  PKPollingController.swift
//  GoAbroad
//
//  Created by Pink Snow on 2025/5/27.
//

import Foundation
import RxSwift
import RxCocoa
import NSObject_Rx
class PKPollingController<T> {
    private var disposable: Disposable?
    private let trigger = PublishSubject<Void>()
    private let stopSignal = PublishSubject<Void>()

    func start<R>(pollInterval: RxTimeInterval,
               fetch: @escaping () -> Observable<R>,
               onNext: @escaping (R) -> Void) {
        guard disposable == nil else { return }

        disposable = trigger
            .flatMapLatest { _ in
                Observable<Int>.interval(pollInterval, scheduler: MainScheduler.instance)
                    .takeUntil(self.stopSignal) // 👈 增加中断控制
            }
            .flatMapLatest { _ in
                fetch().catch { _ in Observable.empty() }
            }
            .observe(on: MainScheduler.instance)
            .subscribe(onNext: onNext)
    }

    func triggerPolling() {
        trigger.onNext(())
    }

    func stop() {
        stopSignal.onNext(())     // 👈 触发中断
        disposable?.dispose()
        disposable = nil
    }
}
